package com.demo.study.thread;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/***
 * 多线程实现求和
 *
 */
public class MyCallableDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("---主程序执行开始---");
        Date dateBegin = new Date();

        //创建一个线程池
        int taskSize = 2;
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
 
        //并发任务的返回值列表
        List<Future> futureList = new ArrayList<>();

        for (int i = 1; i <= taskSize; i++) {
            //创建并发任务,执行并发任务并获取Future对象
            Future future = pool.submit(new MyCallable(i, Integer.valueOf(game(1))));
            futureList.add(future);
            future.get();
        }
 
        //关闭线程池
        pool.shutdown();
        Thread.currentThread().sleep(1000);
        System.out.println("--------------");
 
        //获取所有并发任务的运行结果
        int sum = 0;
        if (!futureList.isEmpty()) {
            for (Future oneFuture : futureList) {
                List<String> stringList = (List<String>) oneFuture.get();
                if (!stringList.isEmpty()) {
                    System.out.println(">>>耗时" + stringList.get(0) + "毫秒" + "---" + "求和结果" + stringList.get(1));
                }
                String s = stringList.get(1);
                sum += Integer.valueOf(s);
            }
            System.out.println("最后执行结果【【【【【【】】】】】】"+sum);

        }
 
        Date dateEnd = new Date();
        long time = dateEnd.getTime() - dateBegin.getTime();
        System.out.println("\n---主程序执行结束,共运行时间【" + time + "】毫秒---");

    }


    /**
     * 获取count个随机数
     * @param count 随机数个数
     * @return
     */
    public static String game(int count){
        StringBuffer sb = new StringBuffer();
        String str = "0123456789";
        Random r = new Random();
        for(int i=0;i<count;i++){
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace((str.charAt(num)+""), "");
        }
        return sb.toString();
    }
}
